package com.lc.advertising.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.advertising.R;
import com.lc.advertising.app.AppActivity;
import com.lc.advertising.http.request.CardAddApi;
import com.lc.advertising.http.request.EditSaveApi;
import com.lc.advertising.http.request.GetCodeApi;
import com.lc.advertising.http.response.RegisterBean;
import com.lc.advertising.manager.InputTextManager;
import com.lc.advertising.other.IntentKey;
import com.lc.advertising.util.BankInfo;
import com.lc.advertising.util.CourseUtils;
import com.lc.advertising.util.SPUtil;
import com.lc.advertising.widget.CountdownView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddBankCartActivity extends AppActivity {
    @BindView(R.id.car_people)
    EditText carPeople;
    @BindView(R.id.car_number)
    EditText carNumber;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.code)
    EditText code;
    @BindView(R.id.cv_register_countdown)
    CountdownView cvRegisterCountdown;
    @BindView(R.id.btn_bank)
    Button btnBank;
    private String name;
    private BankInfo bankinfobean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_addbankcart;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        InputTextManager.with(this)
                .addView(carPeople)
                .addView(carNumber)
                .addView(code)
                .addView(phone)
                .setMain(btnBank)
                .build();
        //EditText监听
        phone.setText(getIntent().getStringExtra("mobile"));
        carPeople.setText(getIntent().getStringExtra("card_people"));
        carNumber.setText(getIntent().getStringExtra("ycardnum"));
        carNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
              String  cardnum = carNumber.getText().toString();
                bankinfobean = new BankInfo(cardnum);
                if (cardnum !=null && checkBankCard(cardnum)) {
                  name= bankinfobean.getBankName();
                    Log.e("TAG", "onTextChanged: "+name );

                }else if(bankinfobean.getCardType().equals("信用卡")){
                    toast("不能绑定信用卡");
                }else {
                   name="";
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // 在输入数据前监听
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 在输入数据后监听
            }
        });
    }

    @OnClick({R.id.image_back, R.id.cv_register_countdown, R.id.btn_bank})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.cv_register_countdown:
                if (CourseUtils.isNullOrEmpty(phone.getText().toString().trim())) {
                    toast("请输入手机号");
                    return;
                }
                EasyHttp.post(this)
                        .api(new GetCodeApi()
                                .setMobile(phone.getText().toString()))
                        .request(new HttpCallback<RegisterBean>(this) {

                            @Override
                            public void onSucceed(RegisterBean data) {
                                toast(data.getMessage());
                                if (data.getCode() == 200) {
                                    cvRegisterCountdown.start();
                                }

                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                                cvRegisterCountdown.start();
                            }
                        });
                break;
            case R.id.btn_bank:
                if (getIntent().getStringExtra("type").equals("修改"))
                    edit_save();
                    else
                card_add();
                break;
        }
    }

    private void edit_save() {
        EasyHttp.post(this)
                .api(new EditSaveApi()
                        .setMobile(phone.getText().toString().trim()).setCardname(name).setCardnum(carNumber.getText().toString().trim()).setName(carPeople.getText().toString().trim()).setYzm(code.getText().toString().trim()).setUid(SPUtil.get(this, IntentKey.UID,"")).setId(getIntent().getStringExtra("id")))
                .request(new HttpCallback<RegisterBean>(this) {

                    @Override
                    public void onSucceed(RegisterBean data) {
                        toast(data.getMessage());
                        if (data.getCode() == 200) {
                            finish();
                        }

                    }


                });
    }

    private void card_add() {
        EasyHttp.post(this)
                .api(new CardAddApi()
                        .setMobile(phone.getText().toString().trim()).setCardname(name).setCardnum(carNumber.getText().toString().trim()).setName(carPeople.getText().toString().trim()).setYzm(code.getText().toString().trim()).setUid(SPUtil.get(this, IntentKey.UID,"")))
                .request(new HttpCallback<RegisterBean>(this) {

                    @Override
                    public void onSucceed(RegisterBean data) {
                        toast(data.getMessage());
                        if (data.getCode() == 200) {
                              finish();
                        }

                    }


                });
    }

    /**校验过程：
     1、从卡号最后一位数字开始，逆向将奇数位(1、3、5等等)相加。
     2、从卡号最后一位数字开始，逆向将偶数位数字，先乘以2（如果乘积为两位数，将个位十位数字相加，即将其减去9），再求和。
     3、将奇数位总和加上偶数位总和，结果应该可以被10整除。
     * 校验银行卡卡号
     */
    public static boolean checkBankCard(String bankCard) {
        if(bankCard.length() < 15 || bankCard.length() > 19) {
            return false;
        }
        char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
        if(bit == 'N'){
            return false;
        }
        return bankCard.charAt(bankCard.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhn 校验算法获得校验位
     * @param nonCheckCodeBankCard
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeBankCard){
        if(nonCheckCodeBankCard == null || nonCheckCodeBankCard.trim().length() == 0
                || !nonCheckCodeBankCard.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeBankCard.trim().toCharArray();
        int luhmSum = 0;
        for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if(j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
    }
}
